package com.example.spring.thread.practice.poll;

import java.util.Random;
import java.util.concurrent.*;

/**
 * @author: orange
 * @create: 2023-09-06 22:11
 * @description:
 */
public class Main1_20230906_2 {
    public static void main(String[] args) {
        ThreadPoolExecutor threadPoolExecutor =
                new ThreadPoolExecutor(1, 1, 0, TimeUnit.SECONDS, new LinkedBlockingDeque<>());
        Future<Integer> submit = threadPoolExecutor.submit(new Generate());
        try {
            Integer g = submit.get();
            threadPoolExecutor.execute(new Guess(g));
            threadPoolExecutor.shutdown();
        } catch (ExecutionException | InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    static class Generate implements Callable<Integer> {
        @Override
        public Integer call() throws Exception {
            return new Random().nextInt(100);
        }
    }

    static class Guess implements Runnable {
        private final Integer val;
        public Guess(Integer val) {
            this.val = val;
        }

        @Override
        public void run() {
            int l = 0, r = 100;
            while (l < r) {
                int mid = l + r >> 1;
                if (mid > val) {
                    r = mid;
                    System.out.format("%d，太大了。\n", mid);
                }
                else if (mid == val) {
                    l = mid;
                    System.out.format("%d，找到了。\n", mid);
                    break;
                }
                else {
                    System.out.format("%d，太小了。\n", mid);
                    l = mid + 1;
                }
            }
        }
    }
}
